
#include"Sock.hpp"
#include<pthread.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<unistd.h>
#include<fstream>

#define WWWROOT "./wwwroot/"
#define HOME_PAGE "index.html"

using namespace std;
void Usig(std::string proc)
{
    cout<<"Usig: "<<proc <<"prot"<<endl;
}

void* HandlerHttpRequest(void *args)
{
    int sock=*(int* )args;
    delete (int* )args;
    pthread_detach(pthread_self());

    char buffer[1024*10];
    memset(&buffer,0,sizeof(buffer));

    ssize_t s=recv(sock,buffer,sizeof(buffer),0);
    if(s>0)
    {
        buffer[s]=0;

        // string http_response="http/1.0 200 \n";
        // http_response+="Content-Type:text/plain\n"; //text/plain 普通文本
        // http_response+="\n";
        // //正文
        // http_response+="good!\n";

        string html_file=WWWROOT;
        html_file+=HOME_PAGE;
        ifstream in(html_file);
        if(!in.is_open())
        {
            string http_response="http/1.0 404 NOT FOUND\n";
            //正文数据
            http_response+="Content-Type: text/html;charset=utf8\n";
            http_response+="\n";
            http_response+="<html><p>你访问的资源不存在</p><html>";
            send(sock,http_response.c_str(),http_response.size(),0);
        }
        else
        {
            struct stat st;
            stat(html_file.c_str(),&st);//stat 函数是用来获取文件的各种属性

            string http_response="http/1.0 20 ok\n";
            http_response+="Content-Type:text/html;charset=utf8\n";
            http_response+="Content-Length: ";
            http_response+=std::to_string(st.st_size);
            http_response+="\n";

            //Set-Cookie:服务器向浏览器设置一个cookie
            http_response+="Set-Cookie:id=222222\n";
            http_response+="Set-Cookie:password=222222\n";
            http_response+="\n";
            
            string content;
            string line;
            while(getline(in,line))
            {
                content+=line;
            }
            http_response+=content;
            in.close();
            send(sock,http_response.c_str(),http_response.size(),0);

        }

    }
    close(sock);
    return nullptr;
}
int main(int argc,char* argv[])
{
    if(argc!=2)
    {
        Usig(argv[0]); exit(1);
    }

    uint16_t prot=atoi(argv[1]);
    int listen_sock=Sock::Socket();
    Sock::Bind(listen_sock,prot);
    Sock::Listen(listen_sock);

    for(;;)
    {
        int sock=Sock::Accept(listen_sock);
        if(sock>0)
        {
            pthread_t tid;
            int *parm=new int(sock);
            pthread_create(&tid,nullptr,HandlerHttpRequest,parm);
        }
    }

    return 0;
}
